/*
 * @lc app=leetcode.cn id=662 lang=typescript
 *
 * [662] 二叉树最大宽度
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

interface Data {
  idx: number;
  node: TreeNode;
}

function widthOfBinaryTree(root: TreeNode | null): number {
  const queue: Data[] = new Array();
  queue.push({ idx: 1, node: root });
  let ans = 1;
  while (queue.length) {
    let n = queue.length;
    ans = Math.max(ans, queue[n - 1].idx - queue[0].idx + 1);
    const offset = queue[n - 1].idx;
    while (n--) {
      const { idx, node } = queue.shift()!;
      if (node.left) queue.push({ idx: idx * 2 - offset, node: node.left });
      if (node.right) queue.push({ idx: idx * 2 + 1 - offset, node: node.right });
    }
  }
  return ans;
}
// @lc code=end
